<?php

namespace app\admin\controller\activity;

use app\common\controller\Backend;
use app\common\model\SignUp;
use Exception;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 活动管理
 *
 * @icon fa fa-circle-o
 */
class Activity extends Backend
{

    /**
     * Activity模型对象
     * @var \app\admin\model\activity\Activity
     */
    protected $model = null;
    protected $application = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\activity\Activity;
        $this->application = new \app\admin\model\activity\Application;

    }

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->alias($this->model->getTableName())
            ->field($this->model->getTableName() . '.*, GROUP_CONCAT(DISTINCT  goods.goods_name) as goods_name, GROUP_CONCAT(DISTINCT group.group_name) as group_name, GROUP_CONCAT(DISTINCT category.name) as cate_name')
            ->join('goods goods', 'find_in_set(goods.id, goods_ids)', 'LEFT')
            ->join('category category', 'find_in_set(category.id, cates_ids)', 'LEFT')
            ->join('group group', 'find_in_set(group.id, group_id)', 'LEFT')
            ->where($where)
            ->order($sort, $order)
            ->group($this->model->getTableName() . '.id')
            ->paginate($limit)->each(function (&$value) {
                // todo 每日打卡数据
                $value['toDayPunchNumber'] = SignUp::instance()
                    ->where(['activity_id' => $value['id']])
                    ->whereTime('createtime', 'today')
                    ->sum('number');
                // todo 最终数据
                $value['punchTotalNumber'] = SignUp::instance()
                    ->where(['activity_id' => $value['id']])
                    ->sum('number');
                // todo 打卡用户昵称
                $punchUser = collection(SignUp::instance()
                    ->alias('t1')
                    ->field('t2.nickname')
                    ->join('user t2', 't1.user_id = t2.id', 'LEFT')
                    ->where(['t1.activity_id' => $value['id']])
                    ->group('t1.user_id')
                    ->select())->toArray();
                $value['punchUserNickname'] = empty($punchUser) ? "" : implode('|', array_column($punchUser, 'nickname'));
            });
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $params['admin_uid'] = $this->auth->id ?? 0;
        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        if (!empty($params['type'])) {
            if ($params['type'] == 1) {
                $params['goods_ids'] = 0;
            }
        }
        $params = array_filter($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params['admin_uid'] = $this->auth->id ?? 0;
        $params = $this->preExcludeFields($params);
        if (!empty($params['type'])) {
            if ($params['type'] == 1) {
                $params['goods_ids'] = 0;
            }
        }
        if (empty($params['startdate'])) {
            unset($params['startdate']);
        }
        if (empty($params['endtime'])) {
            unset($params['endtime']);
        }
        if (empty($params['signup_start_date'])) {
            unset($params['signup_start_date']);
        }
        if (empty($params['signup_end_date'])) {
            unset($params['signup_end_date']);
        }
        if (empty($params['sign_start_date'])) {
            unset($params['sign_start_date']);
        }
        if (empty($params['sign_end_date'])) {
            unset($params['sign_end_date']);
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 查看报名
     * */
    public function detail()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $condition = [];
            if ($ids = $this->request->param('ids')) {
                $condition['activity_id'] = $ids;
            }
            $list = $this->application
                ->with(['user'])
                ->where($where)
                ->where($condition)
                ->paginate($limit);

            foreach ($list as $row) {
                $row->getRelation('user')->visible(['nickname', 'avatar']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            $activity_ids = array_column(collection($list)->toArray(), 'id');
            \app\common\model\Application::instance()->where(['activity_id' => ['in', $activity_ids]])->delete();
            \app\common\model\AwardCeremony::instance()->where(['activity_id' => ['in', $activity_ids]])->delete();
            SignUp::instance()->where(['activity_id' => ['in', $activity_ids]])->delete();
            foreach ($list as $item) {
                $count += $item->delete();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }
}
